package com.example.dormmanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormmanage.dao.IBillsDao;
import com.example.dormmanage.dao.IRoomDao;
import com.example.dormmanage.entity.Bills;
import com.example.dormmanage.entity.Room;
import com.example.dormmanage.service.IBillsService;
import com.example.dormmanage.view.BillsDto;
import com.example.dormmanage.view.ResultView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BillsService extends ServiceImpl<IBillsDao, Bills> implements IBillsService {

    @Autowired
    private IRoomDao roomDao;

    @Autowired
    private BuildingService buildingService;

    //查询楼宇水电费列表
    public ResultView<Page> selectBillsList(Integer page, Integer pageSize, Integer buildingId, String roomName) {
        Page<BillsDto> pageInfo = new Page<>(page, pageSize);
        //根据楼宇id查询宿舍
        LambdaQueryWrapper<Room> roomLqw = new LambdaQueryWrapper<>();
        roomLqw.like(roomName != null, Room::getRoomName, roomName)
                .eq(Room::getBuildingId, buildingId);
        List<Room> roomList = roomDao.selectList(roomLqw);
        //查询每个水电费,封装数据
        List<BillsDto> billsDtoList = roomList.stream().map(item -> {
            BillsDto billsDto = new BillsDto();
            billsDto.setBuildingName(buildingService.getBuildingName(buildingId));
            billsDto.setRoomName(item.getRoomName());
            //查询对应宿舍的水电费
            LambdaQueryWrapper<Bills> billsLqw = new LambdaQueryWrapper<>();
            billsLqw.eq(Bills::getRoomId, item.getRoomId());
            Bills bills = this.getOne(billsLqw);
            BeanUtil.copyProperties(bills, billsDto);//对象赋值
            //计算总额
            Double totalCost = bills.getWaterBills() + bills.getElecBills();
            billsDto.setTotalCost(totalCost);
            return billsDto;
        }).collect(Collectors.toList());
        return ResultView.success(pageInfo.setRecords(billsDtoList));
    }


}
